<!--
 * @Author: zhang_wenjuan
 * @Date: 2021-05-19 16:44:45
 * @LastEditTime: 2021-07-30 09:14:43
 * @Description: 新增隐患
-->

<template>
    <div id="addHiddenDanger_page">
        <!-- 顶部导航 -->
        <van-nav-bar title="添加隐患" left-arrow @click-left="back" fixed>
            <!-- <van-icon class="scan" name="scan" slot="right" size="22" />
            <van-icon name="qr" slot="right" size="22" />
            <template slot="right">
                <div class="parent-circle">
                    <div class="child-circle"></div>
                </div>
            </template> -->
        </van-nav-bar>
        <!-- 占位符 -->
        <div class="kong"></div>
        <!-- 选择区域 -->
        <div class="selectPart">
            <!-- 变电站名称 -->
            <van-field required v-model="addData.substationName" readonly label="变电站名称" input-align="right"
            />
            <!-- 隐患类型 -->
            <van-field @click="showHiddenDangerType=true" required readonly v-model="addData.hiddenDangerTypeName" placeholder="请选择（必选）"
                label="隐患类型" input-align="right" right-icon="arrow" />

            <!-- 隐患名称 -->
            <van-field v-model="addData.hiddenDangerName" label="隐患名称" input-align="right" />

            <!-- 隐患设备 -->
            <van-field @click="showDeviceFlag=true" readonly v-model="addData.deviceName" placeholder="请选择（必选）"
                label="隐患设备" input-align="right" right-icon="arrow" />
                
            <!-- 隐患分级 -->
            <van-field @click="showFenji=true" required readonly v-model="addData.fenjiName" placeholder="请选择（必选）" label="隐患分级"
                input-align="right" right-icon="arrow" />
            <!-- 隐患分类 -->
            <van-field @click="showFenlei=true" required readonly v-model="addData.fenleiName" placeholder="请选择（必选）" label="隐患分类"
                input-align="right" right-icon="arrow" />
            
            <!-- 隐患来源 -->
            <van-field @click="showSource=true" required readonly v-model="addData.sourceName" placeholder="请选择（必选）" label="隐患来源"
                input-align="right" right-icon="arrow" />
            <!-- 共性隐患 -->
            <van-field @click="showGongXing=true" required readonly v-model="addData.gongXingName" placeholder="请选择（必选）" label="共性隐患"
                input-align="right" right-icon="arrow" />
            <!-- 拟采取措施 -->
            <van-field @click="showMeasure=true" required readonly v-model="addData.MeasureName" placeholder="请选择（必选）" label="拟采取措施"
                input-align="right" right-icon="arrow" />
            <!-- 发现人 -->
            <van-field @click="findUserShow=true" required readonly v-model="addData.finderName" placeholder="请选择（必选）" label="发现人"
                input-align="right" right-icon="arrow" />

            <van-field @click="findTimeShow=true" required readonly v-model="addData.discoveryDate" placeholder="请选择（必选）" label="发现时间"
            input-align="right" right-icon="arrow" />
            <!-- 隐患描述 -->
            <div class="descBox">
                <div>隐患描述</div>
                <van-field class="descField" v-model="addData.describeName" rows="2" autosize type="textarea" maxlength="50"
                    placeholder="请输入（必填）" show-word-limit />
            </div>
            <!-- 隐患备注 -->
            <div class="descBox">
                <div>备注</div>
                <van-field class="descField" v-model="addData.remark" rows="2" autosize type="textarea" maxlength="50"
                    placeholder="请输入（必填）" show-word-limit />
            </div>
            <div class="descBox">
                <div>附件：</div>
                <div class="imgItemBox">
                    <div class="fileItem" v-for="(item,i) in fileList" :key="i">
                        <img class="itemImg" :src="item.content" alt="" srcset="">
                        <div class="del">
                            <van-icon name="close" color="#F56C6C" size="24" @click='delImg(i)' />
                        </div>
                    </div>
                    <img src="../../images/addTestData.png" @click="uploadShow=true">
                </div>
            </div>
        </div>
        <!-- 下拉框区域 -->
        <van-popup v-model="showHiddenDangerType" position="bottom">
            <!-- <van-picker show-toolbar :columns="hiddenDangerTypeArr" @confirm="confirmHiddenDangerType"
                @cancel="showHiddenDangerType = false" /> -->
            <van-action-sheet title="隐患类型"
                cancel-text="取消"
                @cancel="showHiddenDangerType=false"
                v-model="showHiddenDangerType"
                :actions="hiddenDangerTypeArr"
                @select="confirmHiddenDangerType"
            />
        </van-popup>
        <!-- 隐患分级下拉弹窗 -->
        <van-popup v-model="showFenji" position="bottom">
            <van-action-sheet title="隐患分级"
                cancel-text="取消"
                @cancel="showFenji=false"
                v-model="showFenji"
                :actions="fenjiArr"
                @select="confirmFenji"
            />
        </van-popup>
        <!-- 隐患分类下拉弹窗 -->
        <van-popup v-model="showFenlei" position="bottom">
            <!-- <van-picker show-toolbar :columns="fenleiArr" @confirm="confirmFenlei" @cancel="showFenlei = false" /> -->
            <van-action-sheet title="隐患分类"
                cancel-text="取消"
                @cancel="showFenlei=false"
                v-model="showFenlei"
                :actions="fenleiArr"
                @select="confirmFenlei"
            />
        </van-popup>
        <!-- 隐患来源下拉弹窗 -->
        <van-popup v-model="showSource" position="bottom">
            <!-- <van-picker show-toolbar :columns="sourceArr" @confirm="confirmSource" @cancel="showSource = false" /> -->
            <van-action-sheet title="隐患来源"
                cancel-text="取消"
                @cancel="showSource=false"
                v-model="showSource"
                :actions="sourceArr"
                @select="confirmSource"
            />
        </van-popup>
        <!-- 拟采取措施下拉弹窗 -->
        <van-popup v-model="showMeasure" position="bottom">
            <!-- <van-picker show-toolbar :columns="measureArr" @confirm="confirmMeasure" @cancel="showMeasure = false" /> -->
            <van-action-sheet title="拟采取措施"
                cancel-text="取消"
                @cancel="showMeasure=false"
                v-model="showMeasure"
                :actions="measureArr"
                @select="confirmMeasure"
            />
        </van-popup>
        <!-- 共性隐患下拉弹窗 -->
        <van-popup v-model="showGongXing" position="bottom">
            <!-- <van-picker show-toolbar :columns="gongXingArr" @confirm="confirmGongXing" @cancel="showGongXing = false" /> -->
            <van-action-sheet title="是否共性隐患"
                cancel-text="取消"
                @cancel="showGongXing=false"
                v-model="showGongXing"
                :actions="gongXingArr"
                @select="confirmGongXing"
            />
        </van-popup>
        <!-- 发现人下拉弹窗 -->
		<van-popup class="selSub" round close-on-click-overlay v-model="findUserShow" position="bottom" @close="findUserShow=false">
            <selPople 
            @comfirmPerson="confirmfindUser" @closePersonPage="findUserShow=false"></selPople>
		</van-popup>

        <!-- 选择设备下拉弹窗 -->
        <van-popup v-model="showDeviceFlag" class="selSub" position="bottom" @close="showDeviceFlag=false">
            <selDevice :single="single" :subId="addData.substationId" @comfirmDevice="confirmDevice" @closeDevicePage="showDeviceFlag=false"></selDevice>
        </van-popup>
        
        <!-- 选择审核人下拉弹窗 -->
        <van-popup v-model="selectExamUser" class="selSub" position="bottom" @close="selectExamUser=false">
            <selPople :title="title" :single="single" @comfirmPerson="confirmExamUser" @closePersonPage="selectExamUser=false"></selPople>
        </van-popup>
        <!-- 日期 -->
        <van-popup round close-on-click-overlay v-model="findTimeShow" position="bottom" @close="findTimeShow=false">
			<van-datetime-picker v-model="currentDate" title="选择时间" @confirm="onConfirm" @cancel="findTimeShow=false" type="datetime">
			</van-datetime-picker>
		</van-popup>

        <van-popup v-model="uploadShow" :style="{ height: '10%' }" position="bottom">
            <div class="selectFile">
                <div class="photo">
                    <img src="../../images/photo.png" @click="photo">
                    <div>开始拍照</div>
                </div>
                <div class="selectImg">
                    <van-uploader class="selectfile" multiple :after-read="afterRead">
                        <img src="../../images/selectFile.png" style="width: 3rem;
                        margin-left: 5rem;
                        margin-top: -0.7rem;">
                        <div style="margin-left: 4.5rem;">选择文件</div>
                    </van-uploader>
                </div>
            </div>
        </van-popup>
        
        <!-- 底部按钮区域 -->
        <div class="footPart">
            <van-button size="small" @click="sumbit('save')">保存</van-button>
            <van-button class="sureBtn" size="small" @click="selectExamUser=true">确认</van-button>
        </div>
    </div>
</template>
<script type="text/javascript">
    import Utils from '@/utils/util'
    import {addHazardInfo,submitHazard} from "../../api/hideDanger"
    import {UploadSignPhoto} from '../../api/common';
    import selSubstation  from "@/components/SelectSubstation"
    import selPople  from "@/components/SelPeople.vue"
    import selDevice  from "@/components/selDevice.vue"
    export default {
        name: "defectList",
        components: {
            selSubstation,
            selPople,
            selDevice
        },
        data() {
            return {
                title: "选择审核人",
                showFenji: false,//是否显示隐患分级下拉弹窗
                showFenlei: false,//是否显示隐患分类下拉弹窗
                showHiddenDangerType: false,//是否显示隐患类型下拉弹窗
                showSource: false,//是否显示隐患来源下拉弹窗
                showGongXing: false,//是否显示共性隐患下拉弹窗
                showMeasure: false,//是否显示拟采取措施下拉弹窗
                findUserShow: false,//是否显示发现人下拉弹窗
                selectExamUser: false,//是否显示审核人下拉弹窗
                findTimeShow: false,//发现时间falg
                uploadShow: false,//附件上传标志
                showDeviceFlag:false,//设备选择开关
                fileList: [],//上传附件
                fenjiArr: [],//隐患分级下拉列表
                fenleiArr: [],//隐患分类下拉列表
                hiddenDangerTypeArr: [],//隐患类型下拉列表
                sourceArr: [],//隐患来源下拉列表
                currentDate: "",
                gongXingArr: [
                    { code: "0", name: "否" },
                    { code: "1", name: "是" }
                ],//共性下拉列表
                measureArr: [],//拟采取措施下拉列表
                addData: {
                    id: "",//任务id
                    substationId: "",//变电站id
                    substationName: "",//变电站名称
                    userId: "",
                    userName:"",
                    hiddenDangerTypeName: "",//隐患类型名称
                    hiddenDangerTypeId: "",//隐患类型id
                    deviceName: "",//设备名称（作为隐患名称）
                    deviceId: "",//设备id
                    fenjiName: "",//隐患分级名称
                    fenjiId: "",//隐患分级id
                    fenleiName: "",//隐患分类名称
                    fenleiId: "",//隐患分类id
                    sourceName: "",//隐患来源名称
                    sourceId: "",//隐患来源id
                    gongXingName: "",//共性隐患名称
                    gongXingId: "",//共性隐患id
                    MeasureName: "",//拟采取措施名称
                    MeasureId: "",//拟采取措施id
                    finderName: "",//发现人名称
                    finderId: "",//发现人id
                    describeName: "",//隐患描述
                    remark: "",//备注
                    uuidList:[],//隐患图片uuid
                    reviewerList:[],//审核人
                    hiddenDangerName: "",//隐患名称
                    discoveryDate: "",
                },
                taskInfo:{},//任务详情
                deviceInfo:{},//设备详情
                single: true
            }
        },
        mounted() {
            var userInfo = localStorage.getItem("userInfo");
            this.userInfo = JSON.parse(userInfo);
            this.taskInfo = this.$route.query.taskInfo;//任务详情
            this.deviceInfo = this.$route.query.deviceInfo;//设备信息
            this.addData.discoveryDate = Utils.DateUtil.getFormatDateByLong(new Date().getTime(),'yyyy-MM-dd hh:mm')
            debugger;
            if(this.taskInfo.id) {
                this.rander();
            }
            this.hiddenDangerTypeArr = Utils.baseUtil.getSpecialCode("HAZARD_TYPE");//隐患类型
            this.fenjiArr = Utils.baseUtil.getSpecialCode("HAZARD_GRADE");//隐患分级
            this.fenleiArr = Utils.baseUtil.getSpecialCode("HAZARD_CATEGORIZE");//隐患分类
            this.sourceArr = Utils.baseUtil.getSpecialCode("HAZARD_SOURCE_TYPE");//隐患来源类型
            this.measureArr = Utils.baseUtil.getSpecialCode("PLAN_TO_TAKE_MEASURES");//隐患来源类型  
        },
        methods: {
            //时间确认按钮
            onConfirm(val){
				this.findTimeShow = false;
            	this.addData.discoveryDate = Utils.DateUtil.getFormatDateByLong(val,'yyyy-MM-dd hh:mm')
            },
            /**
             * @description: 确定选择设备名称
             * @param {*}
             * @return {*}
             */
            confirmDevice(deviceList) {
                this.showDeviceFlag = false;
                this.addData.deviceName = deviceList[0].deviceName;//设备名称
                this.addData.deviceId = deviceList[0].deviceId;
            },
            /**
             * @description: 数据渲染
             */
            rander() {
                this.addData.id = this.taskInfo.id;
                this.addData.substationId = this.taskInfo.substationId;
                this.addData.substationName = this.taskInfo.substationName;//变电站名称
                this.addData.deviceName = this.deviceInfo.deviceName;//设备名称
                this.addData.deviceId = this.deviceInfo.deviceId;
            },
            /**
             * 返回
             */
            back() {
                this.$router.push({
                    name:"executeIndex",
                    params: {
                        taskInfo: this.taskInfo
                    }
                })
            },
            /**
             * @description: 确定选择隐患分级
             * @param {String} val 隐患分级
             */
            confirmFenji(val) {
                this.addData.fenjiName = val.name;
                this.addData.fenjiId = val.code;
                this.showFenji = false
            },

            /**
             * @description: 确定选择隐患分类
             * @param {String} val 隐患分类
             */
            confirmFenlei(val) {
                this.addData.fenleiName = val.name;
                this.addData.fenleiId = val.code;
                this.showFenlei = false
            },

            /**
             * @description: 确定选择隐患类型
             * @param {String} val 隐患类型
             */
            confirmHiddenDangerType(val) {
                this.addData.hiddenDangerTypeName = val.name;
                this.addData.hiddenDangerTypeId = val.code;
                this.showHiddenDangerType = false
            },

            /**
             * @description: 确定选择隐患来源
             * @param {String} val 隐患来源
             */
            confirmSource(val) {
                this.addData.sourceName = val.name;
                this.addData.sourceId = val.code;
                this.showSource = false
            },

            /**
             * @description: 确定选择共性隐患
             * @param {String} val 共性隐患
             */
            confirmGongXing(val) {
                this.addData.gongXingName = val.name;
                this.addData.gongXingId = val.code;
                this.showGongXing = false
            },

            /**
             * @description: 确定选择拟采取措施
             * @param {String} val 拟采取措施
             */
            confirmMeasure(val) {
                this.addData.MeasureName = val.name;
                this.addData.MeasureId = val.code;
                this.showMeasure = false
            },
            /**
             * @description: 确定选择发现人
             * @param {String} val 发现人
             */
            confirmfindUser(personList) {
                this.addData.finderId = personList.map(item => item.userId).join(",");
                this.addData.finderName = personList.map(item => item.userName).join(",");
                this.findUserShow = false
            },
            /**
             * @description: 确认选择审核人
             * @param {*}
             * @return {*}
             */
            confirmExamUser(val) {
                this.selectExamUser = false;
                this.addData.reviewerList = [];
                console.log(val);
                this.addData.reviewerList = val.map(item => {
                    return {
                        auditorId: item.userId,
                        auditorName: item.userName,
                    }
                })
                this.sumbit("commit");//审核人
            },
            /**
             * @description: 提交
             */
            sumbit(type) {
                if (!this.addData.hiddenDangerTypeId) {
                    return this.$toast("请选择隐患类型！");
                }
                if (!this.addData.fenjiId) {
                    return this.$toast("请选择隐患分级名称！");
                }
                if (!this.addData.fenleiId) {
                    return this.$toast("请选择隐患分类名称！");
                }
                if (!this.addData.sourceId) {
                    return this.$toast("请选择隐患来源名称");
                }
                if (!this.addData.gongXingId) {
                    return this.$toast("请选择共性隐患名称");
                }
                if (!this.addData.MeasureId) {
                    return this.$toast("请选择拟采取措施名称");
                }
                if (!this.addData.finderId) {
                    return this.$toast("请选择发现人名称");
                }
                var self = this;
                if(this.fileList.length > 0) {
                    this.updateFile(type);//上传隐患文件
                }else{
                    this.addHiddenDanger(type); 
                }
            },
             /**
             * @description: 组件选择图片成功后的回调函数
             * @param {*}
             * @return {*}
             */
            afterRead(file, detail) {
                console.log("file",file);
                this.fileList.push(...file)
            },
            /**
             * @description: 上传
             * @param {*}
             * @return {*}
             */
            async updateFile(type) {
                this.$Toast.loading({
					duration: 0,//展示时长 0不会消失
					message: "附件上传中...",
					forbidClick: true,//是否禁止背景点击
					overlay: true//是否显示背景遮罩层
				})
                var uuids = this.fileList.map(item => {
                    var formData = new FormData; 
                    formData.append("file", item.file) //文件流
                    formData.append("userId",this.userInfo.userId)
                    formData.append("source","1")//1 维护  0 缺陷  2 隐患
                    return UploadSignPhoto(formData)
                })
				try {                    
                    var list = await Promise.all(uuids);
                    var mapList = [];
                    list.forEach(item => {
                        if(item.success) {
                            mapList.push(
                                {
                                    attachmentName: "",
                                    uuid: item.data
                                }
                            )
                        } 
                    })
                    console.log("list",mapList)
                    this.addHiddenDanger(type,mapList);
                } catch (error) {
                    this.$Toast.clear();
                }
            },
            /**
             * @description: 新增隐患
             * @param {*}
             * @return {*}
             */
            addHiddenDanger(save,mapList) {
                var self = this;
                this.$toast.loading({
                    duration: 0,//展示时长 0不会消失
                    message: "正在创建隐患...",
                    forbidClick: true,//是否禁止背景点击
                    overlay: true//是否显示背景遮罩层
                })
                var params = {
                    userId: this.userInfo.userId,//用户id（必传）
                    roleCode: "",//用户角色（非必传）
                    substationId: this.addData.substationId,//变电站id（必传）
                    substationName: this.addData.substationName,//变电站名称（必传）
                    reviewerList:[],//审核人
                    discoveryPeople: this.addData.finderName,//发现人名称
                    discoveryPeopleId: this.addData.finderId,//发现人id
                    hazardDescription:this.addData.describeName,//隐患描述
                    remarks:this.addData.remark,//备注
                    deviceId: this.addData.deviceId,
                    deviceName: this.addData.deviceName,//设备名称（隐患名称）
                    planToTakeMeasures: this.addData.MeasureName,//拟采取措施
                    isCommonHazard: this.addData.gongXingId,//共性隐患名称
                    hazardSourceType: this.addData.sourceName,//隐患来源id
                    hazardClassify: this.addData.fenleiName,//隐患分类名称
                    hazardGrade: this.addData.fenjiName,//隐患分级名称
                    lastPatrolCyclePlanId: this.addData.id,//任务id
                    hazardType: this.addData.hiddenDangerTypeName,//隐患类型
                    attachmentList: [],//uuid
                }
                if(mapList) {
                    params.attachmentList = mapList;
                }
                addHazardInfo(params).then(function (res) {
                    self.$toast.clear()
                    if (res.success) {
                        if(save == "save") {
                            self.$Dialog.alert({
                                message: '新增隐患成功',
                            }).then(() => {
                                self.$router.push({
                                    name:"executeIndex",
                                    params: {
                                        taskInfo: self.taskInfo
                                    }
                                })
                            });
                        }else{
                            self.$toast.clear(); 
                            self.commitHide(res.data);
                        }
                    }else{
                        self.$toast.fail("隐患新建失败")
                        self.$toast.clear()
                    }
                }).catch(err => {
                    self.$toast.clear()
                });
            },
            /**
             * @description:提交隐患 
             * @param {*}
             * @return {*}
             */
            commitHide(id) {
                var self = this;
                var params = {
                    hazardId: id,//隐患
                    reviewerList: this.addData.reviewerList,//审核人
                    userId: this.userInfo.userId,//登录人
                    roleCode: ""
                }
                submitHazard(params).then(function (res) {
                    self.$toast.clear()
                    if (res.success) {
                        self.$Dialog.alert({
                            message: '新增隐患成功',
                        }).then(() => {
                            self.$router.push({
                                name:"executeIndex",
                                params: {
                                    taskInfo: self.taskInfo
                                }
                            })
                        });
                    }else{
                        self.$toast.fail("隐患新建失败")
                        self.$toast.clear()
                    }
                }).catch(err => {
                    self.$toast.clear()
                });
            },
            /**
             * @description: 开始拍照
             * @param {*}
             * @return {*}
             */
             photo() {
                this.$toast("暂无安卓支持")
            },
            /**
             * @description: 删除附件
             * @param {*} i
             * @return {*}
             */
             delImg(i) {
                this.fileList.splice(i,1);
            },
        },
    }
</script>
<style scoped>
    #addHiddenDanger_page {
        width: 100%;
        height: 100%;
        padding-bottom: 0;
        background: #fff;
    }

    .van-nav-bar {
        background: #17b49b;
    }

    .van-nav-bar /deep/ .van-icon {
        color: #fff;
        font-size: 22px;
    }

    .scan {
        margin-right: 10px;
    }

    .van-nav-bar /deep/ .van-nav-bar__title {
        color: #fff;
        font-size: 18px;
    }

    .van-nav-bar /deep/ .van-button {
        background: #fff;
        color: #17b49b;
        width: 60px;
        border-radius: 4px;
    }

    .kong {
        width: 100%;
        height: 46px;
    }

    /* 选择区域 */
    .selectPart {
        height: calc(100% - 120px);
        overflow-y: auto;
    }

    /* 缺陷描述区域 */
    .descBox {
        padding: 0 16px;
        color: #646566;
        font-size: 14px;
        margin-top: 20px;
    }

    .descBox .descField {
        border: 1px solid #eee;
        margin-top: 10px;
    }

    /* 底部按钮区域 */
    .footPart {
        width: 100%;
        height: 50px;
        position: fixed;
        bottom: 0;
        left: 0;
        border-top: 1px solid #efefef;
        background: #fff;
        text-align: center;
        display: flex;
        justify-content: center;
        align-items: center;
    }

    .footPart .van-button {
        width: 100px;
        margin: 0 10px;
        border-radius: 5px;
    }

    .sureBtn {
        background: #17b49b;
        color: #fff;
    }
    .imgItemBox {
        /* width: 100vw; */
        display: flex;
        flex-wrap: wrap;
    }

    .del {
        position: absolute;
        top: 0;
        right: 0;
    }
    .selectFile {
        width: 100%;
        height: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
    }

    .selectFile>div {
        height: 3rem;
        flex: 1;
        display: flex;
        justify-content: center;
        align-items: center;
        flex-direction: column;
    }

    .selectFile>div>img {
        height: 100%;
    }

    .selectImg {
        border-left: 1px solid #cccccc;
        position: relative;
    }

    .selectfile {
        position: absolute;
        top: 0;
        left: 0;
    }
    .itemImg {
        width: 80px;
        height: 78px;
        /* margin-left: 10px; */
    }

    .fileItem {
        width: 80px;
        height: 78px;
        margin-left: 10px;
        position: relative;
    }
    .selSub{
        height: 100%;
        width: 100%;
    }
    /deep/.van-overlay {
        background-color: rgba(0,0,0,.3);
    }
</style>